import React, { useEffect, useState, useCallback } from 'react'
import { connect } from 'react-redux'
import { NotifyType } from '../../common/enums'
import { getActivePageOfActiveTabSelector, getMockActiveAjaxIdSelector } from '../../selectors/baseSelector'
import { genMockSetActiveAjaxId } from '../../actions/home'
import { SingleSelectableList } from '../layout/singleSelectableList'
import { getAllAjaxsOfPage } from '../../source/getData'
import { notify } from '../../source/notify'
import basicStyle from '../common/basic.scss'
import { EmptyElement } from '../common/emptyElement'
import { ColHeader } from '../common/colHeader'

const maStateToProps = state => {
    return {
        activePage: getActivePageOfActiveTabSelector(state),
        activeAjaxId: getMockActiveAjaxIdSelector(state),
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onSelectItem: ajaxId => dispatch(genMockSetActiveAjaxId(ajaxId)),
    }
}

export const AjaxList = connect(maStateToProps, mapDispatchToProps)((props) => {
    const { activePage, activeAjaxId, onSelectItem } = props
    const [loading, setLoading] = useState(true)
    const [dataSource, setDataSource] = useState([])

    const wrapOnSelectItem = useCallback(item => onSelectItem(item.id), [])

    useEffect(() => {
        setLoading(true)
        getAllAjaxsOfPage(activePage).then((data = []) => {
            setLoading(false)
            setDataSource(data)
            data.length && onSelectItem(data[0].id)
        }).catch(err => {
            setLoading(false)
            setDataSource([])
            notify(NotifyType.error, err)
        })
    }, [activePage])

    const getUrl = useCallback(item => item.url, [])
    const getRemark = useCallback(item => item.remark, [])

    return loading
        ? <div className={basicStyle.basic_loading} />
        : <React.Fragment>
            <ColHeader title='所选页面的网络请求：' />
            {dataSource.length
                ? <SingleSelectableList activeValue={activeAjaxId} dataSource={dataSource} loading={loading}
                    getItemValue={item => item.id} getItemTitle={getUrl} getItemTitle2={getRemark} onSelectItem={wrapOnSelectItem} />
                : <EmptyElement />}
        </React.Fragment>
})